package com.wtb.javatool.action;

import com.fy.wetoband.tool.Tool;
import com.fy.wetoband.utils.RequestUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wtb.javatool.common.Result;
import com.wtb.javatool.dao.ResourceMapper;
import com.wtb.javatool.entity.*;
import com.wtb.javatool.service.ICourseService;
import com.wtb.javatool.service.IDishService;
import com.wtb.javatool.service.IResourceService;
import com.wtb.javatool.util.AliOSSUtils;
import com.wtb.javatool.vo.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Action;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;

@Api(value = "javatool", description = "java工具示例")
@Scope(SCOPE_PROTOTYPE) //务必使用多实例模式
@ComponentScan("com.wtb.javatool")
@Slf4j
public class CourseKnowledgeAction<BandUser> extends Tool {

    @Autowired
    private ICourseService courseService;

    @Autowired
    private IResourceService resourceService;

    @Autowired
    private IDishService dishService;

    @Autowired
    AliOSSUtils aliOSSUtils;

    @Autowired
    private ResourceMapper resourceMapper;


    /**
     * 课程相关接口
     *
     * @param request
     * @param response
     * @return
     */
    @Action
    @ApiOperation(value = "添加课程", httpMethod = "POST", notes = "添加课程信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "course_name", dataType = "string", value = "课程名称", required = true),
            @ApiImplicitParam(name = "description", dataType = "string", value = "课程描述", required = false)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "添加课程成功", response = Result.class)
    })

    public Result<String> saveCourse(HttpServletRequest request, HttpServletResponse response) {

        String course_name = RequestUtil.getStringParameter(request, "course_name");
        String description = RequestUtil.getStringParameter(request, "description");
        Course course = new Course(course_name, description);
        final Integer save = courseService.save(course);
        if (save <= 0) {
            return Result.error("添加课程失败");
        }

        return Result.success("添加课程成功");
    }

    @Action
    public Result<String> helloworld2(HttpServletRequest request, HttpServletResponse response) {
        return Result.success("广州城市理工ni好");
    }

    @Action
    @ApiOperation(value = "修改课程", httpMethod = "POST", notes = "修改课程信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "course_id", dataType = "Integer", value = "课程ID", required = true),
            @ApiImplicitParam(name = "course_name", dataType = "string", value = "课程名称", required = true),
            @ApiImplicitParam(name = "description", dataType = "string", value = "课程描述", required = false)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "修改课程成功", response = Result.class)
    })
    public Result<String> updateCourse(HttpServletRequest request, HttpServletResponse response) {

        Integer course_id = RequestUtil.getIntegerParameter(request, "course_id");
        String course_name = RequestUtil.getStringParameter(request, "course_name");
        String description = RequestUtil.getStringParameter(request, "description");

        Course course = new Course(course_id, course_name, description);
        course.setCourseId(course_id);

        final Integer update = courseService.update(course);
        if (update <= 0) {
            return Result.error("修改课程失败");
        }
        return Result.success("修改课程成功");
    }


    @Action
    @ApiOperation(value = "列出所有课程", httpMethod = "GET", notes = "列出所有课程")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = Result.class)
    })
    public Result<List<CourseDto>> listAllCource(HttpServletRequest request, HttpServletResponse response) {
        List<Course> courses = courseService.listAll();
        if (courses == null || courses.size() == 0) {
            List<CourseDto> list2 = new ArrayList<>();
            list2.add(new CourseDto(1, "调用成功", "数据为空"));
            return Result.success(list2);
        }
        List<CourseDto> list = courses.stream().map(new Function<Course, CourseDto>() {
            @Override
            public CourseDto apply(Course course) {
                CourseDto dto = new CourseDto();
//                BeanUtils.copyProperties(course, dto);
                if (course != null) {
                    BeanUtils.copyProperties(course, dto);
                }

                return dto;
            }
        }).collect(Collectors.toList());
        System.out.println(Result.success());
        return Result.success(list);
    }

    @Action
    @ApiOperation(value = "删除课程", httpMethod = "POST", notes = "删除课程信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "course_id", dataType = "Integer", value = "课程ID", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "添加课程成功", response = Result.class)
    })
    public Result<String> deleteCourse(HttpServletRequest request, HttpServletResponse response) {

        Integer course_id = RequestUtil.getIntegerParameter(request, "course_id");

        final Integer delete = courseService.delete(course_id);
        if (delete <= 0) {
            return Result.error("删除课程失败");
        }
        return Result.success("删除课程成功");
    }

    @Action
    @ApiOperation(value = "根据课程名称模糊搜索课程", httpMethod = "GET", notes = "根据课程名称模糊搜索课程信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "course_name", dataType = "Integer", value = "课程名称", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "根据课程名称模糊搜索课程", response = Result.class)
    })
    public Result<List<CourseDto>> selectCourseByName(HttpServletRequest request, HttpServletResponse response) {
        String course_name = RequestUtil.getStringParameter(request, "course_name");
        List<Course> courses = courseService.selectCourseByName(course_name);
        if (courses == null || courses.size() == 0) return null;
        List<CourseDto> list = courses.stream().map(new Function<Course, CourseDto>() {
            @Override
            public CourseDto apply(Course course) {
                CourseDto dto = new CourseDto();
                if (course != null) {
                    BeanUtils.copyProperties(course, dto);
                }
                //  BeanUtils.copyProperties(course, dto);
                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }

    /**
     * 资源相关接口
     */

    @Action
    @ApiOperation(value = "根据课程id搜索该课程下的所有资源信息", httpMethod = "GET", notes = "根据课程id搜索该课程下的所有资源信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "course_id", dataType = "Integer", value = "课程名称", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "根据课程id搜索该课程下的所有资源信息", response = Result.class)
    })
    public Result<List<ResourceDto>> selectResourceByCourseId(HttpServletRequest request, HttpServletResponse response) {
        Integer course_id = RequestUtil.getIntegerParameter(request, "course_id");
        List<Resource> resources = resourceService.selectResourceByCourseId(course_id);
        if (resources == null || resources.size() == 0) return null;
        List<ResourceDto> list = resources.stream().map(new Function<Resource, ResourceDto>() {
            @Override
            public ResourceDto apply(Resource resource) {
                ResourceDto dto = new ResourceDto();
                if (resource != null) {
                    BeanUtils.copyProperties(resource, dto);
                }

                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }

    @Action
    @ApiOperation(value = "根据资源分类id搜索分类名称", httpMethod = "GET", notes = "根据资源分类id搜索分类名称")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource_type_id", dataType = "Integer", value = "分类id", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "根据资源分类id搜索分类名称", response = Result.class)
    })
    public Result<String> selectResourceTypeById(HttpServletRequest request, HttpServletResponse response) {
        Integer resource_type_id = RequestUtil.getIntegerParameter(request, "resource_type_id");
        String resource_type_name = resourceService.selectResourceTypeById(resource_type_id);
        return Result.success(resource_type_name);
    }

    @Action
    @ApiOperation(value = "资源分类列表", httpMethod = "GET", notes = "资源分类列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "资源分类列表", response = Result.class)
    })
    public Result<List<ResourceType>> resourceTypeList(HttpServletRequest request, HttpServletResponse response) {
        List<ResourceType> list = resourceService.resourceTypeList();
        if (list == null || list.size() == 0) return null;
        return Result.success(list);
    }

    //    @Action
//    @ApiOperation(value = "根据资源类型id搜索资源信息", httpMethod = "GET", notes = "根据资源类型id搜索资源信息")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "resource_type_id", dataType = "Integer", value = "分类id", required = true),
//    })
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "根据资源类型id搜索资源信息", response = Result.class)
//    })
//    public Result<List<Resource>> selectResourseByResourseTypeId(HttpServletRequest request, HttpServletResponse response) {
//        Integer resource_type_id = RequestUtil.getIntegerParameter(request, "resource_type_id");
//        List<Resource> resources = resourceService.selectResourseByResourseTypeId(resource_type_id);
//        if(resources==null || resources.size()==0) return null;
//        List<ResourceDto> list = resources.stream().map(new Function<Resource, ResourceDto>() {
//            @Override
//            public ResourceDto apply(Resource resource) {
//                ResourceDto dto = new ResourceDto();
//                if(resource!=null){
//                    BeanUtils.copyProperties(resource, dto);
//                }
//
//                return dto;
//            }
//        }).collect(Collectors.toList());
//        return Result.success(resources);
//    }
    @Action
    @ApiOperation(value = "根据资源类型id搜索资源信息", httpMethod = "GET", notes = "根据资源类型id搜索资源信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource_type_id", dataType = "Integer", value = "分类id", required = true),
            @ApiImplicitParam(name = "course_id", dataType = "Integer", value = "分类id", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "根据资源类型id搜索资源信息", response = Result.class)
    })
    public Result<List<Resource>> selectResourseByResourseTypeId(HttpServletRequest request, HttpServletResponse response) {
        Integer resource_type_id = RequestUtil.getIntegerParameter(request, "resource_type_id");
        Integer course_id = RequestUtil.getIntegerParameter(request, "course_id");
        List<Resource> resources = resourceService.selectResourseByResourseTypeId(resource_type_id, course_id);
        if (resources == null || resources.size() == 0) return null;
        List<ResourceDto> list = resources.stream().map(new Function<Resource, ResourceDto>() {
            @Override
            public ResourceDto apply(Resource resource) {
                ResourceDto dto = new ResourceDto();
                if (resource != null) {
                    BeanUtils.copyProperties(resource, dto);
                }

                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(resources);
    }

    @Action
    @ApiOperation(value = "上传资源", httpMethod = "POST", notes = "上传资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource_name", dataType = "string", value = "资源名称", required = true),
            @ApiImplicitParam(name = "resource_type_id", dataType = "int", value = "资源分类id", required = true, defaultValue = "1"),
            @ApiImplicitParam(name = "resource_data", dataType = "file", value = "资源图片", required = false),
            @ApiImplicitParam(name = "user_id", dataType = "int", value = "上传者", required = true),
            @ApiImplicitParam(name = "course_id", dataType = "int", value = "上传者", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "上传资源", response = Result.class)
    })
    public Result<String> uploadResource(HttpServletRequest request, HttpServletResponse response) {
        String resource_name = RequestUtil.getStringParameter(request, "resource_name");
        Integer resource_type_id = RequestUtil.getIntegerParameter(request, "resource_type_id");
        Integer user_id = RequestUtil.getIntegerParameter(request, "user_id");
        Integer course_id = RequestUtil.getIntegerParameter(request, "course_id");
        // 1. 检查是否为 multipart 请求
        if (!ServletFileUpload.isMultipartContent(request)) {
            return Result.error("请求必须为 multipart/form-data 类型");
        }

        // 2. 配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(10 * 1024 * 1024); // 10MB 文件大小限制

        try {
            // 3. 解析请求
            List<FileItem> items = upload.parseRequest(request);
            byte[] fileData = null;
            String mimeType = null; // 新增字段

            // 4. 提取参数和文件
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // 普通表单字段
                    switch (item.getFieldName()) {
                        case "resource_name":
                            resource_name = item.getString("UTF-8");
                            break;
                        case "resource_type_id":
                            resource_type_id = Integer.parseInt(item.getString("UTF-8"));
                            break;
                        case "user_id":
                            user_id = Integer.parseInt(item.getString("UTF-8"));
                            break;
                        case "course_id":
                            course_id = Integer.parseInt(item.getString("UTF-8"));
                            break;
                    }
                } else {
                    // 文件字段
                    if ("resource_data".equals(item.getFieldName())) {
                        fileData = item.get();
                        try (InputStream is = item.getInputStream()) {
                            mimeType = URLConnection.guessContentTypeFromStream(is);
                        }
                    }
                }
            }

            // 5. 验证必要参数
            if (StringUtils.isEmpty(resource_name) || StringUtils.isEmpty(resource_type_id)) {
                return Result.error("资源名称和类型不能为空");
            }
            if (fileData == null || fileData.length == 0) {
                return Result.error("请上传有效的资源文件");
            }

            // 6. 构建资源对象
            Resource resource = new Resource();
            resource.setResourceName(resource_name);
            resource.setResourceTypeId(resource_type_id);
            resource.setResourceData(fileData);
            resource.setResourceSize(fileData.length / 1024 + "KB");
            resource.setUploadUserId(user_id);
            resource.setMimeType(mimeType);
            // 调用服务层
            boolean success = resourceService.uploadResource(
                    resource_name,
                    resource_type_id, // 直接传递long类型
                    fileData,
                    fileData.length / 1024 + "KB",
                    user_id,
                    course_id,
                    mimeType
            );
            return success ? Result.success("上传成功") : Result.error("上传失败");

        } catch (Exception e) {
            return Result.error("系统错误: " + e.getMessage());
        }
    }

    //    @Action
//    @ApiOperation(value = "上传资源", httpMethod = "POST", notes = "上传资源")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "resource_name", dataType = "string", value = "资源名称", required = true),
//            @ApiImplicitParam(name = "resource_type_id", dataType = "int", value = "资源分类id", required = true, defaultValue = "1"),
//            @ApiImplicitParam(name = "resource_data", dataType = "file", value = "资源图片", required = false)
//    })
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "上传资源", response = Result.class)
//    })
//    public Result<String> uploadResource2(HttpServletRequest request, HttpServletResponse response) throws IOException {
//
//        String resource_name = RequestUtil.getStringParameter(request, "resource_name");
//        Integer resource_type_id = RequestUtil.getIntegerParameter(request, "resource_type_id");
//        MultipartFile file = null;
//        if (ServletFileUpload.isMultipartContent(request)) {
//            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getServletContext());
//            MultipartHttpServletRequest multiRequest = multipartResolver.resolveMultipart(request);
//            file = multiRequest.getFile("resource_data");
//        }
//        String url = aliOSSUtils.upload(file);
//        System.out.println(url);
//
//        return Result.success(url);
//
//    }
    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file, HttpServletRequest request)
            throws IOException {
        String url = aliOSSUtils.upload(file);
        return Result.success(url);
    }

    @Action
    @ApiOperation(value = "根据资源id获取资源图片", httpMethod = "GET", notes = "根据资源id获取资源图片")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource_id", dataType = "Integer", value = "资源id", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "根据资源id获取资源图片", response = Result.class)
    })
    public Result<Resource> selectResourceDataByResourceId(HttpServletRequest request, HttpServletResponse response) {
        Integer resource_id = RequestUtil.getIntegerParameter(request, "resource_id");
        Resource resource_data = resourceService.selectResourceDataByResourceId(resource_id);
        if (resource_data == null) {
            return Result.error("资源不存在");
        }
        //已学习人数+1
        Integer add = resourceService.addLearnersCount(resource_id);
        // String base64images = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(resource_data);
        return Result.success(resource_data);
    }

//    /**
//     * 根据多个资源类型id搜索资源信息
//     */
//    @Action
//    @ApiOperation(value = "根据资源类型id搜索资源信息", httpMethod = "GET", notes = "根据资源类型id搜索资源信息")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "resource_type_id_list", dataType = "String", value = "分类id集合", required = true),
//    })
//    @ApiResponses({
//            @ApiResponse(code = 200, message = "根据资源类型id搜索资源信息", response = Result.class)
//    })
//    public Result<List<ResourceDto>> selectResourseByResourseTypeIdList(HttpServletRequest request, HttpServletResponse response) {
//        String resource_type_id_list = RequestUtil.getStringParameter(request, "resource_type_id_list");
//        List<Integer> resourceTypeIds = Arrays.stream(resource_type_id_list
//                .split(","))
//                .map(String::trim)
//                .map(Integer::parseInt)
//                .collect(Collectors.toList());
//        List<Resource> resources = resourceService.selectResourseByResourseTypeIdList(resourceTypeIds);
//        if(resources==null || resources.size()==0) return null;
//        List<ResourceDto> list = resources.stream().map(new Function<Resource, ResourceDto>() {
//            @Override
//            public ResourceDto apply(Resource resource) {
//                ResourceDto dto = new ResourceDto();
//                if(resource!=null){
//                    BeanUtils.copyProperties(resource, dto);
//                }
//                return dto;
//            }
//        }).collect(Collectors.toList());
//        return Result.success(list);
//    }

    /**
     * 根据多个资源类型id搜索资源信息
     */
    @Action
    @ApiOperation(value = "根据资源类型id搜索资源信息", httpMethod = "GET", notes = "根据资源类型id搜索资源信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource_type_id_list", dataType = "String", value = "分类id集合", required = true),
            @ApiImplicitParam(name = "course_id", dataType = "int", value = "课程id", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "根据资源类型id搜索资源信息", response = Result.class)
    })
    public Result<List<ResourceDto>> selectResourseByResourseTypeIdList(HttpServletRequest request, HttpServletResponse response) {
        String resource_type_id_list = RequestUtil.getStringParameter(request, "resource_type_id_list");
        Integer course_id = RequestUtil.getIntegerParameter(request, "course_id");
        if (resource_type_id_list == null) return null;
        List<Integer> resourceTypeIds = Arrays.stream(resource_type_id_list
                        .split(","))
                .map(String::trim)
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        List<Resource> resources = resourceService.selectResourseByResourseTypeIdList(resourceTypeIds, course_id);
        if (resources == null || resources.size() == 0) return null;
        List<ResourceDto> list = resources.stream().map(new Function<Resource, ResourceDto>() {
            @Override
            public ResourceDto apply(Resource resource) {
                ResourceDto dto = new ResourceDto();
                if (resource != null) {
                    BeanUtils.copyProperties(resource, dto);
                }
                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }

    /**
     * 资源收藏
     */
    @Action
    @ApiOperation(value = "资源收藏", httpMethod = "POST", notes = "资源收藏")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource_id", dataType = "int", value = "资源id", required = true),
            @ApiImplicitParam(name = "user_id", dataType = "int", value = "用户id", required = true, defaultValue = "1")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "资源收藏成功", response = Result.class)
    })
    public Result<String> saveresourceFavorite(HttpServletRequest request, HttpServletResponse response) {
        Integer resource_id = RequestUtil.getIntegerParameter(request, "resource_id");
        Integer user_id = RequestUtil.getIntegerParameter(request, "user_id");
        Favorite favorite = new Favorite(resource_id, user_id);
        final Integer save = resourceService.saveresourceFavorite(favorite);
        if (save <= 0) {
            return Result.error("资源收藏失败");
        }

        return Result.success("资源收藏成功");
    }

    /**
     * 获取资源收藏列表
     */
    @Action
    @ApiOperation(value = "获取资源收藏列表", httpMethod = "GET", notes = "获取资源收藏列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource_id", dataType = "int", value = "资源id", required = true),
            @ApiImplicitParam(name = "user_id", dataType = "int", value = "用户id", required = true, defaultValue = "1")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取资源收藏列表成功", response = Result.class)
    })
    public Result<List<FavoriteDto>> listAllResourceFavorite(HttpServletRequest request, HttpServletResponse response) {
        Integer resource_id = RequestUtil.getIntegerParameter(request, "resource_id");
        Integer user_id = RequestUtil.getIntegerParameter(request, "user_id");
        Favorite favorite = new Favorite(resource_id, user_id);
        List<Favorite> favorites = resourceService.listAllResourceFavorite(favorite);
        if (favorites == null || favorites.size() == 0) {
            return Result.success(null);
        }

        List<FavoriteDto> list = favorites.stream().map(new Function<Favorite, FavoriteDto>() {
            @Override
            public FavoriteDto apply(Favorite favorite) {
                FavoriteDto dto = new FavoriteDto();
                if (favorites != null) {
                    BeanUtils.copyProperties(favorite, dto);
                }

                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }

    /**
     * 资源发表评论和评分
     */
    @Action
    @ApiOperation(value = "资源发表评论和评分", httpMethod = "POST", notes = "资源发表评论和评分")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource_id", dataType = "int", value = "资源id", required = true),
            @ApiImplicitParam(name = "user_id", dataType = "int", value = "用户id", required = true, defaultValue = "1"),
            @ApiImplicitParam(name = "comment_content", dataType = "String", value = "评论内容", required = true, defaultValue = "1"),
            @ApiImplicitParam(name = "score", dataType = "double", value = "评分", required = true, defaultValue = "1")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "资源发表评论和评分成功", response = Result.class)
    })
    public Result<String> saveResourceComment(HttpServletRequest request, HttpServletResponse response) {
        Integer resource_id = RequestUtil.getIntegerParameter(request, "resource_id");
        Integer user_id = RequestUtil.getIntegerParameter(request, "user_id");
        String comment_content = RequestUtil.getStringParameter(request, "comment_content");
        Double score = RequestUtil.getDoubleParameter(request, "score");
        Comment comment = new Comment(comment_content, user_id, resource_id, score);
        final Integer save = resourceService.saveResourceComment(comment);
        if (save <= 0) {
            return Result.error("资源发表评论和评分失败");
        }
        //更新资源已评论人数
        Integer add1 = resourceService.addCommentCount(resource_id);
        //更新资源的总评分
        Integer add2 = resourceService.addTotalScore(comment);
        //查询更新后的已评论人数和总评分
        Resource resource = resourceService.selectCommentCountandTotalScore(resource_id);
        //更新资源的平均分
        Integer add3 = resourceService.addScore(resource);
        return Result.success("资源发表评论和评分成功");
    }

    /**
     * 给资源点赞
     */
    @Action
    @ApiOperation(value = "点赞资源", httpMethod = "POST", notes = "点赞资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource_id", dataType = "int", value = "资源id", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "点赞资源成功", response = Result.class)
    })
    public Result<String> updateLikeCount(HttpServletRequest request, HttpServletResponse response) {
        Integer resource_id = RequestUtil.getIntegerParameter(request, "resource_id");
        final Integer update = resourceService.updateLikeCount(resource_id);
        if (update <= 0) {
            return Result.error("点赞资源成功");
        }
        return Result.success("点赞资源成功");
    }

    /**
     * 查看该资源的所有评论信息
     */
    @Action
    @ApiOperation(value = "查看该资源的所有评论信息", httpMethod = "GET", notes = "查看该资源的所有评论信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource_id", dataType = "int", value = "资源id", required = true),
            @ApiImplicitParam(name = "user_id", dataType = "int", value = "用户id", required = true, defaultValue = "1")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "查看该资源的所有评论信息成功", response = Result.class)
    })
    public Result<List<CommentDto>> listAllResourceComment(HttpServletRequest request, HttpServletResponse response) {
        Integer resource_id = RequestUtil.getIntegerParameter(request, "resource_id");
        Integer user_id = RequestUtil.getIntegerParameter(request, "user_id");
        Comment comment = new Comment(user_id, resource_id);
        List<Comment> comments = resourceService.listAllResourceComment(comment);
//        if(comments == null || comments.size() == 0){
//            return Result.success(null);
//        }
        List<CommentDto> list = comments.stream().map(new Function<Comment, CommentDto>() {
            @Override
            public CommentDto apply(Comment comment) {
                CommentDto dto = new CommentDto();
                BeanUtils.copyProperties(comment, dto);
                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }

    /**
     * 根据用户id查询用户名
     */
    @Action
    @ApiOperation(value = "根据用户id查询用户名", httpMethod = "GET", notes = "根据用户id查询用户名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user_id", dataType = "int", value = "用户id", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "根据用户id查询用户名", response = Result.class)
    })
    public Result<String> selectUserNameByUserId(HttpServletRequest request, HttpServletResponse response) {
        Integer user_id = RequestUtil.getIntegerParameter(request, "user_id");
        String user_name = resourceService.selectUserNameByUserId(user_id);
        return Result.success(user_name);
    }

    /**
     * 下载资源
     */
    @Action
    @ApiOperation(value = "下载资源", httpMethod = "POST", notes = "下载资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource_id", dataType = "Integer", value = "资源id", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "下载资源成功", response = Result.class)
    })
    public ResponseEntity<byte[]> downloadResource(HttpServletRequest request) {
        Integer resourceId = RequestUtil.getIntegerParameter(request, "resource_id");
        Resource resource = resourceMapper.selectResourceDataByResourceId(resourceId);

        if (resource == null || resource.getResourceData() == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        byte[] fileBytes = resource.getResourceData();
        String fileType = resource.getMimeType() != null ? resource.getMimeType() : "application/octet-stream";
        String fileName = resource.getResourceName();

        // 如果文件名为空，设置一个默认文件名
        if (fileName == null || fileName.isEmpty()) {
            fileName = "default_filename";
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(fileType));
        headers.setContentLength(fileBytes.length);

        try {
            // 对文件名进行 URL 编码，避免乱码问题
            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            // 如果编码失败，可以设置一个默认文件名
            fileName = "default_filename";
        }

        headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");

        return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
    }



    /**
     * 根据资源名称和课程id模糊搜索资源
     * @param request
     * @param response
     * @return
     */
    @Action
    @ApiOperation(value = "根据资源名称和课程id模糊搜索资源", httpMethod = "GET", notes = "根据资源名称和课程id模糊搜索资源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "resource_name", dataType = "String", value = "资源名称", required = true),
            @ApiImplicitParam(name = "course_id", dataType = "Integer", value = "课程id", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "根据资源名称和课程id模糊搜索资源", response = Result.class)
    })
    public Result<List<ResourceDto>> selectResourceByName(HttpServletRequest request, HttpServletResponse response) {
        String resource_name = RequestUtil.getStringParameter(request, "resource_name");
        Integer course_id = RequestUtil.getIntegerParameter(request, "course_id");
        List<Resource> resources = resourceService.selectResourceByName(resource_name,course_id);
        if(resources==null || resources.size()==0) return null;
        List<ResourceDto> list = resources.stream().map(new Function<Resource, ResourceDto>() {
            @Override
            public ResourceDto apply(Resource resource) {
                ResourceDto dto = new ResourceDto();
                if (resource != null) {
                    BeanUtils.copyProperties(resource, dto);
                }
                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }
    /**
     * 菜单接口-用于测试使用
     */
    @Action
    @ApiOperation(value = "添加菜品", httpMethod = "POST", notes = "添加菜品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", dataType = "string", value = "菜品名称", required = true),
            @ApiImplicitParam(name = "price", dataType = "string", value = "菜品价格", required = true, defaultValue = "1"),
            @ApiImplicitParam(name = "desc", dataType = "string", value = "菜品描述", required = false)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "添加菜品成功", response = Result.class)
    })
    public Result<String> saveDish(HttpServletRequest request, HttpServletResponse response) {

        String name = RequestUtil.getStringParameter(request, "name");
        String price = RequestUtil.getStringParameter(request, "price");
        String desc = RequestUtil.getStringParameter(request, "desc");

        Dish dish = new Dish(name, new BigDecimal(price), desc);

        final Integer save = dishService.save(dish);
        if(save <= 0){
            return Result.error("添加菜品失败");
        }

        return Result.success("添加菜品成功");
    }

    @Action
    public Result<String> helloworld1(HttpServletRequest request, HttpServletResponse response) {
        return Result.success("广州城市理工你好");
    }

    @Action
    @ApiOperation(value = "修改菜品", httpMethod = "POST", notes = "修改菜品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", dataType = "string", value = "菜品ID", required = true),
            @ApiImplicitParam(name = "name", dataType = "string", value = "菜品名称", required = true),
            @ApiImplicitParam(name = "price", dataType = "string", value = "菜品价格", required = true, defaultValue = "1"),
            @ApiImplicitParam(name = "desc", dataType = "string", value = "菜品描述", required = false)
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "修改菜品成功", response = Result.class)
    })
    public Result<String> updateDish(HttpServletRequest request, HttpServletResponse response) {

        Long dishId = RequestUtil.getLongParameter(request, "dishId");
        String name = RequestUtil.getStringParameter(request, "name");
        String price = RequestUtil.getStringParameter(request, "price");
        String desc = RequestUtil.getStringParameter(request, "desc");

        Dish dish = new Dish(name, new BigDecimal(price), desc);
        dish.setId(dishId);

        final Integer update = dishService.update(dish);
        if (update<=0){
            return Result.error("修改菜品失败");
        }
        return Result.success("修改菜品成功");
    }


    @Action
    @ApiOperation(value = "列出所有菜品", httpMethod = "GET", notes = "列出所有菜品")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = Result.class)
    })
    public Result<List<DishDto>> listAll(HttpServletRequest request, HttpServletResponse response) {
        List<Dish> dishes = dishService.listAll();
        if(dishes == null || dishes.size() == 0){
            return Result.success(null);
        }

        List<DishDto> list = dishes.stream().map(new Function<Dish, DishDto>() {
            @Override
            public DishDto apply(Dish dish) {
                DishDto dto = new DishDto();
                BeanUtils.copyProperties(dish, dto);
                return dto;
            }
        }).collect(Collectors.toList());
        return Result.success(list);
    }

    @Action
    @ApiOperation(value = "删除菜品", httpMethod = "POST", notes = "删除菜品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", dataType = "long", value = "菜品ID", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "添加菜品成功", response = Result.class)
    })
    public Result<String> deleteDish(HttpServletRequest request, HttpServletResponse response) {

        Long dishId = RequestUtil.getLongParameter(request, "dishId");

        final Integer delete = dishService.delete(dishId);
        if (delete<=0){
            return Result.error("删除菜品失败");
        }
        return Result.success("删除菜品成功");
    }

}